import { ReactNode, useEffect, useState } from "react";
import { ModeDarkIcon, ModeLightIcon } from "tdesign-icons-react";
import "./index.scss";
import { error } from "console";
import { Loading } from "tdesign-react";

interface SwitchProps {
  // 默认打开
  defaultValue?: boolean;
  // 异步操作
  asyncChange?: (value: boolean) => Promise<any>;
  // 打开插槽
  openSlot?: ReactNode;
  // 关闭插槽
  closeSlot?: ReactNode;
  // 切换事件
  onChange?: (value: boolean) => void;
}

/**
 * 开关组件
 * @returns
 */
const Switch: React.FC<SwitchProps> = ({ defaultValue, asyncChange, openSlot, closeSlot, onChange }) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [isOpen, setIsOpen] = useState<boolean>(!!defaultValue);
  // 主题切换
  const onSwitchChange = () => {
    // 是否为异步切换
    if (!asyncChange) {
      setIsOpen(!isOpen);
      if (onChange) {
        onChange(!isOpen);
      }
      return;
    }

    setLoading(true);
    asyncChange(!isOpen).then(() => {
        setIsOpen(!isOpen);
        if (onChange) {
          onChange(!isOpen);
        }
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        setLoading(false);
      });
  };
  
  return (
    <div className={`switch__wrap ${isOpen ? "is-open" : ""}`}>
      <div className="left" onClick={onSwitchChange}>
        {closeSlot || '关'}
      </div>
      <div className="right" onClick={onSwitchChange}>
        { openSlot || '开'  }
      </div>

      {/* 滑块 */}
      <div className={`side__button ${isOpen ? 'is-open' : ''}  ${loading ? "is-loading" : ""}`} onClick={onSwitchChange}>
        { loading ? <Loading className="loading" size="12px"></Loading> : '' }
        {
          (openSlot || closeSlot) ? 
            isOpen ? openSlot : closeSlot
            : isOpen ? '开' : '关' 
        }
      </div>
    </div>
  )
};

export default Switch;
